package org.mybatis.jpetstore.test.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;

public class SimpleSocket {
	private Socket client;
	private String host = "127.0.0.1";
	private int port = 9999;
	
	public SimpleSocket(){
		try{
			this.client = new Socket(InetAddress.getByName(this.host),this.port);
			System.out.println("connect to "+this.host+"successful");
			
			BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
			BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
			BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
			
			System.out.println("Start...");
			
			boolean done = false;
			byte[] bytes = new byte[client.getReceiveBufferSize()];
			int len = 0;
			while(!done){
				len = bis.read(bytes);
				if(len == -1)
					done = true;
				else{
					String recieve = new String (bytes,0,len);
					System.out.println(recieve);
					bos.write(systemIn.readLine().getBytes());
					bos.flush();
				}
			}
			System.out.println("Stop...");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(client != null){
					client.close();
				}
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		SimpleSocket ssocket = new SimpleSocket();
	}
	

}
